/**
 * 公司 API 服务
 */

// 开发环境使用代理，生产环境使用实际地址
const API_BASE_URL = import.meta.env.DEV ? '' : 'https://hyyai.com/travel';

/**
 * 获取已入驻的公司列表
 * @returns {Promise<Array>} 公司列表
 */
export async function fetchSettledCompanies() {
  try {
    const response = await fetch(`${API_BASE_URL}/investment_company/page`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    
    // API 返回格式: { code: 200, data: { list: [...], total: 1 }, msg: "" }
    if (result.code === 200 && result.data && result.data.list) {
      return result.data.list;
    }
    
    return [];
  } catch (error) {
    console.error('获取公司列表失败:', error);
    throw error;
  }
}

/**
 * 获取单个公司的详细信息
 * @param {number|string} companyId - 公司ID
 * @returns {Promise<Object>} 公司详细信息
 */
export async function fetchCompanyDetails(companyId) {
  try {
    const response = await fetch(`${API_BASE_URL}/investment_company/get/${companyId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    
    // API 返回格式: { code: 200, data: {...}, msg: "" }
    if (result.code === 200 && result.data) {
      return transformCompanyData(result.data);
    }
    
    throw new Error(result.msg || '获取公司详情失败');
  } catch (error) {
    console.error('获取公司详情失败:', error);
    throw error;
  }
}

/**
 * 将 API 返回的数据转换为应用所需的格式
 * @param {Object} apiCompany - API 返回的公司数据
 * @returns {Object} 格式化后的公司数据
 */
export function transformCompanyData(apiCompany) {
  const companyName = apiCompany.companyName || apiCompany.name || '';
  const firstChar = companyName.charAt(0) || 'C';
  
  return {
    id: apiCompany.id,
    name: companyName,
    logo: apiCompany.logoUrl || apiCompany.logo || `https://via.placeholder.com/120x120/165DFF/FFFFFF?text=${firstChar}`,
    industry: apiCompany.industry || apiCompany.industryType || '未知行业',
    description: apiCompany.introduction || apiCompany.description || apiCompany.intro || apiCompany.companyIntro || '暂无简介',
    establishedYear: apiCompany.establishedYear || apiCompany.foundYear || new Date().getFullYear(),
    employees: apiCompany.employees || apiCompany.employeeCount || '未知',
    revenue: apiCompany.revenue || apiCompany.annualRevenue || '未知',
    address: apiCompany.address || apiCompany.location || apiCompany.companyAddress || '未知',
    website: apiCompany.website || apiCompany.officialWebsite || '',
    tags: Array.isArray(apiCompany.tags) ? apiCompany.tags : (Array.isArray(apiCompany.labels) ? apiCompany.labels : []),
    isSettled: apiCompany.isSettled !== undefined ? apiCompany.isSettled : true,
    settledDate: apiCompany.settledDate || apiCompany.joinDate || '',
    contactInfo: {
      phone: apiCompany.phone || apiCompany.contactPhone || apiCompany.tel || '',
      email: apiCompany.email || apiCompany.contactEmail || '',
    },
  };
}
